import QtQuick 1.1
import com.nokia.meego 1.0
import "Logic.js" as Logic

Page {
    id: pageSettings

    property int numShow
    property int numWords
    property int numWordsFalse
    property int numWordsTrue
    property int numShowTrue
    property int numShowFalse

    onVisibleChanged: {
        if( visible ) {
            topErrorWords()
            topCorrectWords()

            var v = Logic.getNumShow()
            if ( v  !== "" )
                pageSettings.numShow = v
            else
                pageSettings.numShow = 0

            v = Logic.getNumWords()
            if ( v  !== "" )
                pageSettings.numWords = v
            else
                pageSettings.numWords = 0

            v = Logic.getNumWordsOnlyFalse()
            if ( v  !== "" )
                pageSettings.numWordsFalse = v
            else
                pageSettings.numWordsFalse = 0

            v = Logic.getNumWordsOnlyTrue()
            if ( v  !== "" )
                pageSettings.numWordsTrue = v
            else
                pageSettings.numWordsTrue = 0

            v = Logic.getNumShowTrue()
            if ( v  !== "" )
                pageSettings.numShowTrue = v
            else
                pageSettings.numShowTrue = 0

            v = Logic.getNumShowFalse()
            if ( v  !== "" )
                pageSettings.numShowFalse = v
            else
                pageSettings.numShowFalse = 0
        }
    }

    tools: ToolBarLayout {
        id: tool_only_back
        opacity: userTheme.opacityToolbar
        ToolIcon {
            id: toolIconBack
            //iconId: "toolbar-back"
            iconSource: "images/toolbar/back.png"
            onClicked: {
                pageStack.pop();
            }
        }
        ToolIcon {
            //iconId: "toolbar-view-menu"
            iconSource: "images/toolbar/properties.png"
            anchors.right: parent === undefined ? undefined : parent.right
            onClicked: (menuSettings.status == DialogStatus.Closed) ? menuSettings.open() : menuSettings.close()
        }
    } //ToolBarLayout

    Menu {
        id: menuSettings
        visualParent: pageStack
        MenuLayout {
            MenuItem { text: qsTr("Reset all statistics"); onClicked: { dlgResetStat.open() } }
        }
    }

    QNMTitle {
        id: titlePage
        text: qsTr("Settings")
        image: "images/settings.png"
        busy: false
    }

    BackgroundPage { }


    /********************************************************************/
    function createImport() {
         var component = Qt.createComponent( "ImportWords.qml" );
         if ( component.status == Component.Ready ) {
             finishCreation( component );
         } else {
             component.statusChanged.connect( finishCreation );
         }
     }

     function finishCreation( component ) {
         if (component.status == Component.Ready) {
             //sprite = component.createObject(appWindow, {"x": 100, "y": 100});
             var sprite = component.createObject(pageSettings, {});
             if (sprite == null) {
                 // Error Handling
                 console.log("Error creating object");
             }
         } else if (component.status == Component.Error) {
             // Error Handling
             console.log("Error loading component:", component.errorString());
         }
     }
    /********************************************************************/

    Flickable {
        id: flicktextArea
        anchors {
            top: titlePage.bottom
            bottom: parent.bottom
            left: parent.left
            right: parent.right
            topMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 5 : 10
            leftMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 40 : 10
            rightMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 40 : 10
            bottomMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 5 : 10
        }

        contentWidth: contentDescr.width
        contentHeight: contentDescr.height

        clip: true

        Column {
            id: contentDescr
            width: flicktextArea.width
            spacing: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 5 : 10

            MyButton {
                id: btImport
                height: 100
                width: parent.width
                text: qsTr("Import of words")
                iconSource: "images/import.png"
                onClicked: {
                    //createImport()
                    Logic.openFile("ImportWordPage.qml")
                }
            }

            MyButton {
                id: btExport
                height: 100
                width: parent.width
                text: qsTr("Export of words")
                iconSource: "images/export.png"
                onClicked: {
                    //createImport()
                    Logic.openFile("ExportWordPage.qml")
                }
            }

            Item { height: 40; width: parent.width }

            /*
            Text {
                font.pixelSize: 30
                text: qsTr("Language:")
            }
            Button {
                id: btLang
                height: 100
                width: parent.width
                text: ""
                onClicked: {
                }
            }
            */
            //Item { height: 40; width: parent.width }

            Text {
                font.pixelSize: 32
                font.bold: true
                anchors.horizontalCenter: parent.horizontalCenter
                text: qsTr("Statistics")
            }

            /* Число слов в БД*/
            Text {
                font.pixelSize: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 26 : 20
                text: qsTr("The total number of words in the database") + ": "
            }
            Text {
                font.pixelSize: 30
                anchors.horizontalCenter: parent.horizontalCenter
                text:  numWords
            }

            /* Общее число ответов */
            Text {
                font.pixelSize: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 26 : 20
                text: qsTr("The total number of answers") + ": "
            }
            Text {
                font.pixelSize: 30
                anchors.horizontalCenter: parent.horizontalCenter
                text: numShow
            }

            /* Общее число верных ответов */
            Text {
                font.pixelSize: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 26 : 20
                text: qsTr("The total number of correct answers") + ": "
            }
            Row {
                width: parent.width
                Text {
                    text: numShowTrue + "/" + numShow
                    font.pixelSize: 22;
                    width: parent.width*0.3
                    clip: true
                }
                MyProgressBar {
                    id: pCor
                    height: 30
                    width: 0.7*parent.width
                    minValue: 0
                    maxValue: numShow
                    value: numShowTrue
                    color: "green"
                }
            }

            /* Общее число неверных ответов*/
            Text {
                font.pixelSize: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 26 : 20
                text: qsTr("The total number of incorrect answers") + ": "
            }
            Row {
                width: parent.width
                Text {
                    text: numShowFalse + "/" + numShow
                    font.pixelSize: 22;
                    width: parent.width*0.3
                    clip: true
                }
                MyProgressBar {
                    id: pInc
                    height: 30
                    width: 0.7*parent.width
                    minValue: 0
                    maxValue: numShow
                    value: numShowFalse
                    color: "red"
                }
            }

            /* Среднее число ответов на одно слово */
            Text {
                font.pixelSize: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 26 : 20
                text: qsTr("The average number of answers to one word") + ": "
            }
            Text {
                font.pixelSize: 30
                anchors.horizontalCenter: parent.horizontalCenter
                text: numWords != 0 ? Math.round(numShow / numWords) : 0
            }

            /* Число слов только с правильными ответами */
            Text {
                font.pixelSize: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 26 : 19
                text: qsTr("The number of words only with the correct answers") + ": "
            }
            Row {
                width: parent.width
                Text {
                    text: numWordsTrue + "/" + numWords
                    font.pixelSize: 22;
                    width: parent.width*0.3
                    clip: true
                }
                MyProgressBar {
                    height: 30
                    width: 0.7*parent.width
                    minValue: 0
                    maxValue: numWords
                    value: numWordsTrue
                    color: "lightblue"
                }
            }

            /* Число слов без правильных ответов */
            Text {
                font.pixelSize: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 26 : 20
                text: qsTr("The number of words without correct answers") + ": "
            }
            Row {
                width: parent.width
                Text {
                    text: numWordsFalse + "/" + numWords
                    font.pixelSize: 22;
                    width: parent.width*0.3
                    clip: true
                }
                MyProgressBar {
                    height: 30
                    width: 0.7*parent.width
                    minValue: 0
                    maxValue: numWords
                    value: numWordsFalse
                    color: "orange"
                }
            }

            Item { height: 40; width: parent.width }

            Text {
                font.pixelSize: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 26 : 19
                text: qsTr("Top 20 words with the greatest number of errors")
            }
            Rectangle {
                id: frameErrorWords
                height: 400
                width: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? parent.width - 60 : parent.width - 10
                anchors.horizontalCenter: parent.horizontalCenter
                radius: 10
                border.color: "gray"
                border.width: 3
                color: "transparent"
                Component {
                    id: itemDelegate
                    Rectangle {
                        height: 80
                        width: frameErrorWords.width
                        //anchors.horizontalCenter: frameErrorWords.horizontalCenter
                        border.color: "gray"
                        color: "transparent"
                        gradient: Gradient {
                            GradientStop { position: 0; color: "transparent" }
                            GradientStop { position: 1; color: "lightgrey" }
                        }
                        radius: 10
                        Item{
                            id: s1
                            clip: true
                            anchors.top: parent.top
                            anchors.left: parent.left
                            anchors.leftMargin: 20
                            width: parent.width - 40
                            height: parent.height/3
                            Text{ anchors.verticalCenter: parent.verticalCenter; font.pixelSize: 22; text: cppMeeWords.remEnter(model_word) }
                        }
                        Item {
                            id: s2
                            clip: true
                            anchors.top: s1.bottom
                            anchors.left: parent.left
                            anchors.leftMargin: 20
                            width: parent.width - 40
                            height: parent.height/3
                            Text{ anchors.verticalCenter: parent.verticalCenter; font.pixelSize: 22; text: cppMeeWords.remEnter(model_translation) }
                        }
                        Item {
                            id: s3
                            anchors.top: s2.bottom
                            anchors.left: parent.left
                            anchors.leftMargin: 20
                            width: parent.width*0.8
                            height: parent.height/3
                            Row {
                                anchors.centerIn: parent
                                width: parent.width
                                height: parent.height
                                Text {
                                    font.pixelSize: 20;
                                    anchors.verticalCenter: parent.verticalCenter
                                    text: show_error + "/" + word_show
                                    width: parent.width * 0.2
                                }
                                MyProgressBar {
                                    anchors.verticalCenter: parent.verticalCenter
                                    width: parent.width*0.8
                                    height: parent.height*0.8
                                    minValue: 0
                                    maxValue: word_show
                                    value: show_error
                                    color: "red"
                                }
                            }

                        }
                    }
                }
                ListView {
                    id: listViewErrorWords
                    anchors.fill: parent
                    anchors.centerIn: parent
                    clip: true
                    model: listModelErrorWords
                    delegate: itemDelegate
                }
            } //Rectangle

            Item { height: 40; width: parent.width }

            /*---------------------------------------------*/
            Text {
                font.pixelSize: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 26 : 19
                text: qsTr ("Top 20 words with the least number of errors")
            }
            Rectangle {
                id: frameCorrectWords
                height: 400
                width: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? parent.width - 60 : parent.width - 10
                anchors.horizontalCenter: parent.horizontalCenter
                radius: 10
                border.color: "gray"
                border.width: 3
                color: "transparent"

                Component {
                    id: itemDelegateCorrect
                    Rectangle {
                        height: 80
                        width: frameCorrectWords.width
                        border.color: "gray"
                        color: "transparent"
                        gradient: Gradient {
                            GradientStop { position: 0; color: "transparent" }
                            GradientStop { position: 1; color: "lightgrey" }
                        }
                        radius: 10
                        Item {
                            id: s1_c
                            clip: true
                            anchors.top: parent.top
                            anchors.left: parent.left
                            anchors.leftMargin: 20
                            width: parent.width - 40
                            height: parent.height/3
                            Text { anchors.verticalCenter: parent.verticalCenter; font.pixelSize: 22; text: cppMeeWords.remEnter(model_word) }
                        }
                        Item {
                            id: s2_c
                            clip: true
                            anchors.top: s1_c.bottom
                            anchors.left: parent.left
                            anchors.leftMargin: 20
                            width: parent.width - 40
                            height: parent.height/3
                            Text { anchors.verticalCenter: parent.verticalCenter; font.pixelSize: 22; text: cppMeeWords.remEnter(model_translation) }
                        }
                        Item {
                            id: s3_c
                            anchors.top: s2_c.bottom
                            anchors.left: parent.left
                            anchors.leftMargin: 20
                            width: parent.width*0.8
                            height: parent.height/3
                            Row {
                                anchors.centerIn: parent
                                width: parent.width
                                height: parent.height
                                Text {
                                    font.pixelSize: 20;
                                    anchors.verticalCenter: parent.verticalCenter
                                    text: show_error + "/" + word_show
                                    width: parent.width * 0.2
                                }
                                MyProgressBar {
                                    anchors.verticalCenter: parent.verticalCenter
                                    width: parent.width*0.8
                                    height: parent.height*0.8
                                    minValue: 0
                                    maxValue: word_show
                                    value: show_error
                                    color: "green"
                                }
                            }

                        }
                    }
                }
                ListView {
                    id: listViewCorrectWords
                    anchors.fill: parent
                    anchors.centerIn: parent
                    clip: true
                    model: listModelCorrectWords
                    delegate: itemDelegateCorrect
                }
            } //Rectangle
            /*---------------------------------------------*/

            Item { height: 40; width: parent.width }

        }

    } //Flickable

    ListModel {
        id: listModelErrorWords
        Component.onCompleted: topErrorWords()
    }

    ListModel {
        id: listModelCorrectWords
        Component.onCompleted: topCorrectWords()
    }

    /*************************************************************************/
    /* топ 20 слов с наибольшим кол-вом ошибок */
    function topErrorWords() {
        listModelErrorWords.clear()
        var db = Logic.getDatabase()
        db.transaction( function(tx) {
                           var res = tx.executeSql(
                                   "SELECT *, (show_true +show_false) as show FROM "+
                                   "words WHERE show >= ROUND(0.5*(SELECT MAX(show_true +show_false) FROM words)) AND show_false <> 0 "+
                                   "ORDER BY show_false DESC, show DESC LIMIT 20"
                                   )
                           for(var i = 0; i<=res.rows.length-1; i++) {
                               var _word = res.rows.item(i).word;
                               var _translation = res.rows.item(i).translation;
                               var _show = res.rows.item(i).show;
                               var _show_false = res.rows.item(i).show_false;
                               listModelErrorWords.append (
                                           {
                                               model_word: _word,
                                               model_translation: _translation,
                                               word_show: _show,
                                               show_error: _show_false
                                           } );
                           }
                       }
                    )
    }

    /* топ 20 слов с наименьшим кол-вом ошибок */
    function topCorrectWords() {
        listModelCorrectWords.clear()
        var db = Logic.getDatabase()
        db.transaction( function(tx) {
                           var res = tx.executeSql(
                                   "SELECT *, (show_true +show_false) as show FROM "+
                                   "words WHERE show >= ROUND(0.5*(SELECT MAX(show_true +show_false) FROM words)) AND show_true <> 0 "+
                                   "ORDER BY show_true DESC, show DESC LIMIT 20"
                                   )
                           for(var i = 0; i<=res.rows.length-1; i++) {
                               var _word = res.rows.item(i).word;
                               var _translation = res.rows.item(i).translation;
                               var _show = res.rows.item(i).show;
                               var _show_true = res.rows.item(i).show_true;
                               listModelCorrectWords.append (
                                           {
                                               model_word: _word,
                                               model_translation: _translation,
                                               word_show: _show,
                                               show_error: _show_true
                                           } );
                           }
                       }
                    )
    }
    /*************************************************************************/

    QueryDialog {
        id: dlgResetStat
        message: qsTr("Reset al statistics ?")
        acceptButtonText: qsTr("Reset")
        rejectButtonText: qsTr("Cancel")
        onAccepted: {
            var res = Logic.clearAllStatistics()
            if( res === false ) {
                console.log("Reset statistics failed !")
            }
            pageSettings.visibleChanged()
        }
    }

}
